package eiisan.crypto.demo;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class HmacDemo {

    public static void main(String[] args) {
        encrypt("Hello","aaaaaaaaaa");
    }

    /**
     * JDK的实现方式  BC略
     * @param content
     * @param key
     */
    public static void encrypt(String content,String key){
        SecretKey secretKey = getSecretKey(key);

        try {
            Mac mac= Mac.getInstance(secretKey.getAlgorithm());

            //初始化mac
            mac.init(secretKey);
            byte[] hmacMD5Bytes=mac.doFinal(content.getBytes());

            //jdk hmacMD5: bfb61695a42d5d16add45743a4e0eea4
            System.out.println("jdk hmacMD5: "+ Hex.encodeHexString(hmacMD5Bytes));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取默认密钥
     * @return
     */
    public static SecretKey getDefaultSecretKey() {
        SecretKey secretKey = null;
        //初始化KeyGenerator
        KeyGenerator keyGenerator = null;
        try {
            keyGenerator = KeyGenerator.getInstance("HmacMD5");
            //产生密钥
            secretKey = keyGenerator.generateKey();


        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return secretKey;
    }

    /**
     * 自定义密钥
     * @param key
     * @return
     */
    public static SecretKey getSecretKey(String key){
        SecretKey secretKey = null;
        byte[] keyByteArr= null;
        try {
            //长度必须偶数
            boolean flag = (null == key) || ((key.length()) & 1) != 0;
            if(flag){
                throw new DecoderException("Key长度必须偶数");
            }
            keyByteArr = Hex.decodeHex(key.toCharArray());
            secretKey = new SecretKeySpec(keyByteArr,"HmacMD5");
        } catch (DecoderException e) {
            e.printStackTrace();
        }
        return secretKey;
    }

}